package com.example.mine_platform.controller.admin;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.mine_platform.commom.Result;
import com.example.mine_platform.commom.Sex;
import com.example.mine_platform.exception.CustomException;
import com.example.mine_platform.pojo.dto.UserDTO;
import com.example.mine_platform.pojo.entities.User;
import com.example.mine_platform.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/admin")
@CrossOrigin(origins = "*")
public class UserController {
@Resource
    UserService userService;
    @GetMapping("/user/search")
    Result getallUser(@RequestParam(value="userName", required=false)String userName,
                   @RequestParam(value="pageSize", defaultValue="5")Integer pageSize,
                   @RequestParam(value="pageNum",  defaultValue="1")Integer pageNum){
        PageInfo<User> infos=userService.findBySearch(userName,pageSize,pageNum);
     return  Result.success(infos);
}
    @GetMapping("/user/{id}")
    Result getUserMessage(@PathVariable("id")Integer id){
        User user=userService.getById(id);
        UserDTO userDTO=UserDTO.builder()
                .id(user.getId())
                .phone(user.getPhone())
                .userName(user.getUserName())
                .level(user.getLevel())
                .sex(Sex.getValueByCode(user.getSex()))
                .build();
        return Result.success(userDTO);
    }
    @PutMapping("/user/update")
    Result updateUser(@RequestBody UserDTO userDTO){
        User user=User.builder()
                .id(userDTO.getId())
                .userName(userDTO.getUserName())
                .level(userDTO.getLevel())
                .sex(Sex.getCodeByValue(userDTO.getSex()))
                .build();
        userService.update(user);
        return Result.success();
    }
    @GetMapping("/user/exp")
    public void export(HttpServletResponse response) throws IOException {
        log.info("执行...");
            //一行一行的写数据
            //每一行数据，就对应数据库的一条数据，即Type
            //需要一个map<key,value>映射数据,将map放入list
            //1、从数据库中查询所有数据
            List<User> user_all = userService.findAll();
            if(ObjectUtil.isEmpty(user_all)){
                throw new CustomException("下载失败,未找到数据");
            }

            //2、定义list和map处理数据
            List<Map<String, Object>> list = new ArrayList<>(user_all.size());
            //3、遍历封装map将数据放入list
            for(User user : user_all){
                Map<String, Object> row = new HashMap<>();

                row.put("姓名",user.getUserName());
                row.put("手机号",user.getPhone());
                row.put("性别",Sex.getValueByCode(user.getSex()));
                row.put("权限",user.getLevel());
                list.add(row);
            }
            //4、创建一个excelwriter，吧list用write写出来
            ExcelWriter writer = ExcelUtil.getWriter(true);
            writer.write(list,true);
            //5、下载excel
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition","attachment;filename=user.xlsx");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            writer.close();
            //IoUtil.close(System.out);
    }
}
